import * as TYPES from "../action-types";
import {
  getSongDetail,
  getLyric,
  getSimiPlayList,
  getSimiSong,
} from "services/play.js";
import { getRandomNumber } from "@/utils/math-utils";
import { parseLyric } from "@/utils/parse-lyric";

let actions = {
  // redux-promise
  getSongDetail: (id) => {
    return async (dispatch, getState) => {
      // 1.根据id查找playList中是否已经有了该歌曲
      const playList = getState().getIn(["play", "playList"]);
      const songIndex = playList.findIndex((song) => song.id === id);
      let songs = null;
      // 判断是否找到该歌曲
      if (songIndex !== -1) {
        dispatch(actions.changeCurrentSongIndexAction(songIndex));
        dispatch(actions.changeCurrentSongAction(playList[songIndex]));
      } else {
        await getSongDetail({ ids: id })
          .then((res) => {
            songs = res.songs && res.songs[0];
            if (!songs) return;
            // 将最新请求到的歌曲添加到播放列表中
            const newPlayList = [...playList];
            newPlayList.push(songs);
            dispatch(
              actions.changeCurrentSongIndexAction(newPlayList.length - 1)
            );
            dispatch(actions.changeCurrentSongAction(songs));
            dispatch(actions.changePlayListAction(newPlayList));
          })
          .catch((err) => console.log(err));
      }
      // 拿到歌词
      if (!songs) return;
      dispatch(actions.getLyricData(id));
    };
  },
  getLyricData: (id) => {
    return {
      type: TYPES.CHANGE_LYRIC_LIST,
      payload: getLyric({ id }).then((res) => res && parseLyric(res.lrc)),
    };
  },
  getSimiPlayList: () => {
    return async (dispatch, getState) => {
      const id = getState().getIn(["play", "currentSong"]).id;
      const res = await getSimiPlayList({ id });
      dispatch({
        type: TYPES.SIMI_PLAY_LIST,
        payload: res.playlists || [],
      });
    };
  },
  getSimiSongList: () => {
    return async (dispatch, getState) => {
      const id = getState().getIn(["play", "currentSong"]).id;
      const res = await getSimiSong({ id });
      dispatch({
        type: TYPES.SIMI_SONG,
        payload: res.songs || [],
      });
    };
  },
  // redux-thunk
  changeSequence: (idx) => {
    return (dispatch) => {
      dispatch({
        type: TYPES.CHANGE_SEQUENCE,
        payload: idx,
      });
    };
  },
  // 同步 仅供调用
  changeCurrentSongAction: (songs) => ({
    type: TYPES.CHANGE_CURRENT_SONG,
    payload: songs,
  }),
  changePlayListAction: (playList) => ({
    type: TYPES.CHANGE_PLAY_LIST,
    payload: playList,
  }),
  changeCurrentSongIndexAction: (index) => ({
    type: TYPES.CHANGE_CURRENT_SONG_INDEX,
    payload: index,
  }),
  setLyricIdx: (idx) => {
    return {
      type: TYPES.CHANGE_CURRENT_LYRIC_INDEX,
      payload: idx,
    };
  },

  //点击按钮 切换歌曲
  changePlay: (tag) => {
    return (dispatch, getState) => {
      const playList = getState().getIn(["play", "playList"]);
      let currentSongIndex = getState().getIn(["play", "currentSongIndex"]);
      let sequence = getState().getIn(["play", "sequence"]);

      switch (sequence) {
        case 1: //随机播放
          let randomIndex = getRandomNumber(playList.length);
          while (randomIndex === currentSongIndex) {
            randomIndex = getRandomNumber(playList.length);
          }
          currentSongIndex = randomIndex;
          break;

        default:
          //循环
          currentSongIndex += tag;
          if (currentSongIndex >= playList.length) currentSongIndex = 0;
          if (currentSongIndex < 0) currentSongIndex = playList.length - 1;
          break;
      }
      const currentSong = playList[currentSongIndex];
      dispatch(actions.getLyricData(currentSong.id));
      dispatch(actions.changeCurrentSongAction(currentSong));
      dispatch(actions.changeCurrentSongIndexAction(currentSongIndex));
    };
  },
};

export default actions;
